package me.stone.stanimeclient.page.updated

import androidx.paging.PagingSource
import androidx.paging.PagingState
import me.stone.stanimeclient.core.data.domain.data.LoadRecentUpdateListRepository
import me.stone.stanimeclient.core.model.FanSimpleItem

class RecentlyUpdatedPagingSource(
    private val repository: LoadRecentUpdateListRepository
) : PagingSource<Int, FanSimpleItem>() {

    override fun getRefreshKey(state: PagingState<Int, FanSimpleItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, FanSimpleItem> {
        return try {
            val page = params.key ?: 1
            val data = repository.loadRecentUpdateList(page, params.loadSize)
            val nextPage = if (data.currentPage < data.totalPage) page + 1 else null
            val prevPage = if (page > 1) page - 1 else null
            LoadResult.Page(
                data = data.data,
                nextKey = nextPage,
                prevKey = prevPage
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

}